package com.xuhzhiguang.youdao.cli;

import org.apache.commons.cli.*;

import java.util.stream.Collectors;

public class Main {

    private final static HelpFormatter hf = new HelpFormatter();

    private final static Options OPTIONS = new Options();

    static {
        hf.setWidth(110);

        Option helpOpt = new Option("h", "help", false, "帮助");
        helpOpt.setRequired(false);
        OPTIONS.addOption(helpOpt);
    }

    public static void main(String[] args) {

        CommandLine commandLine = null;
        CommandLineParser parser = new DefaultParser();
        try {
            commandLine = parser.parse(OPTIONS, args);
            if (commandLine.hasOption('h')) {
                // 打印使用帮助
                printHelp();
            } else if (commandLine.getArgList().isEmpty()) {
                printHelp();
            } else {
                String word = String.join(" ", commandLine.getArgList());
                printTranslate(word);
            }
        } catch (ParseException e) {
            printHelp();
        }
    }

    private static void printHelp() {
        hf.printHelp("fy <WORD_TO_QUERY>", OPTIONS, true);
    }

    private static void printTranslate(String word) {

        Spinner spinner = new Spinner();
        spinner.start();
        try {
            String result = YoudaoTranslateUtils.translate(word);
            spinner.interrupt();
            spinner.join();
            System.out.println(result);
        } catch (Exception e) {
            spinner.interrupt();
            e.printStackTrace();
        }
    }

}
